<!DOCTYPE html>
<html>

<head>
    <!-- 页面meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>商品编辑</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
  
    <link rel="stylesheet" href="/plugins/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="/plugins/adminLTE/css/AdminLTE.css">
    <link rel="stylesheet" href="/plugins/adminLTE/css/skins/_all-skins.min.css">
    <link rel="stylesheet" href="/css/style.css">
	<script src="/plugins/jQuery/jquery-2.2.3.min.js"></script>
    <script src="/plugins/bootstrap/js/bootstrap.min.js"></script>
    
    <!-- 富文本编辑器 -->
	<link rel="stylesheet" href="/plugins/kindeditor/themes/default/default.css" />
	<script charset="utf-8" src="/plugins/kindeditor/kindeditor-min.js"></script>
	<script charset="utf-8" src="/plugins/kindeditor/lang/zh_CN.js"></script>
    
    
	<!--文件上传-->
    <link rel="stylesheet" href="/plugins/bootstrap-fileinput/css/fileinput.css">
	<script charset="utf-8" src="/plugins/bootstrap-fileinput/js/fileinput.js"></script>
	<script charset="utf-8" src="/plugins/bootstrap-fileinput/js/locales/zh.js"></script>

</head>

<body class="hold-transition skin-red sidebar-mini" >

            <!-- 正文区域 -->
            <section class="content">

                <div class="box-body">

                    <!--tab页-->
                    <div class="nav-tabs-custom">

                        <!--tab头-->
                        <ul class="nav nav-tabs">                       		
                            <li class="active">
                                <a href="#home" data-toggle="tab">商品基本信息</a>                                                        
                            </li>   
                            <li >
                                <a href="#pic_upload" data-toggle="tab">商品图片</a>                                                        
                            </li>    
                            <li >
                                <a href="#customAttribute" data-toggle="tab">扩展属性</a>                                                        
                            </li>     
                            <li >
                                <a href="#spec" data-toggle="tab" >规格</a>                                                        
                            </li>                       
                        </ul>
                        <!--tab头/-->
						
                        <!--tab内容-->
                        <div class="tab-content">

                            <!--表单内容-->
                            <div class="tab-pane active" id="home">
                                <div class="row data-type">                                  
								   <div class="col-md-2 title">商品分类</div>
		                          
		                           	  <div class="col-md-10 data">
		                           	  	<table>
		                           	  		<tr>
		                           	  			<td>
		                           	  				<select class="form-control" id="oneItemCat" onchange="changeOptions(1)" >
		                           	  				</select>
		                              			</td>
		                              			<td>
		                           	  				<select class="form-control select-sm" id="twoItemCat" onchange="changeOptions(2)" ></select>
		                              			</td>
		                              			<td>
		                           	  				<select class="form-control select-sm" id="threeItemCat" onchange="itemCat()" ></select>
		                              			</td>
		                              			<td>
		                           	  				<span  id="templateId">模板id</span>
		                              			</td>
		                           	  		</tr>
		                           	  	</table>
		                              	
		                              </div>	                              
		                          	  
									
		                           <div class="col-md-2 title">商品名称</div>
		                           <div class="col-md-10 data">
		                               <input type="text" class="form-control"  id="goodsName"   placeholder="商品名称" value="">
		                           </div>
		                           
		                           <div class="col-md-2 title">品牌</div>
		                           <div class="col-md-10 data">
		                              <select class="form-control" id="brand" ></select>
		                           </div>
		
								   <div class="col-md-2 title">副标题</div>
		                           <div class="col-md-10 data">
		                               <input type="text" class="form-control"  id="caption"  placeholder="副标题" value="">
		                           </div>
		                           
		                           <div class="col-md-2 title">价格</div>
		                           <div class="col-md-10 data">
		                           	   <div class="input-group">
			                          	   <span class="input-group-addon">¥</span>
			                               <input type="text" class="form-control" id="price"  placeholder="价格" value="">
		                           	   </div>
		                           </div>
		                           
		                           <div class="col-md-2 title editer">商品介绍</div>
                                   <div class="col-md-10 data editer">
                                       <textarea name="content"  style="width:800px;height:400px;visibility:hidden;" id="introduction" ></textarea>
                                   </div>
		                           
		                           <div class="col-md-2 title rowHeight2x">包装列表</div>
		                           <div class="col-md-10 data rowHeight2x">
		                               
		                           	<textarea rows="4"  class="form-control" id="packageList"  placeholder="包装列表"></textarea>
		                           </div>
		                           
		                           <div class="col-md-2 title rowHeight2x">售后服务</div>
		                           <div class="col-md-10 data rowHeight2x">
		                               <textarea rows="4"  class="form-control" id="saleService"   placeholder="售后服务"></textarea>
		                           </div>                        
                                  
                                    
                                </div>
                            </div>
                            
                            <!--图片上传-->
                            <div class="tab-pane" id="pic_upload">
                                <div class="row data-type">                                  
								 <!-- 颜色图片 -->
								 <div class="btn-group">
					                 <button type="button" class="btn btn-default" title="新建" data-target="#uploadModal"  data-toggle="modal"  ><i class="fa fa-file-o"></i> 新建</button>
                             		                 
					             </div>
								 
								 <table class="table table-bordered table-striped table-hover dataTable">
					                    <thead>
					                        <tr>
					                            
											    <th class="sorting">颜色</th>
											    <th class="sorting">图片</th>
												<th class="sorting">操作</th>
							            </thead>
					                    <tbody id="table">

<!--					                      <tr>					                           -->
<!--									            <td>-->
<!--									            	-->
<!--									            </td>-->
<!--									            <td>-->
<!--									           		<img alt="" src="" width="100px" height="100px">	            	 -->
<!--									            </td>-->
<!--												 <td> <button type="button" class="btn btn-default" title="删除" ><i class="fa fa-trash-o"></i> 删除</button></td> -->
<!--					                      </tr>-->
					                    </tbody>
								 </table> 
								  
                                </div>
                            </div>
                           
                           
                            <!--扩展属性-->
                            <div class="tab-pane" id="customAttribute">
                                <table >
									<tbody id="extend"></tbody>
                                </table>
                            </div>
                      
                            <!--规格-->
                            <div class="tab-pane" id="spec">
                            	<div class="row data-type">
	                            	<div class="col-md-2 title">是否启用规格</div>
			                        <div class="col-md-10 data">
			                        	<input type="checkbox" >			                           
			                        </div>
                            	</div>
                            	<p>
                            	
                            	<div>
                            	
	                                <div class="row data-type" id="dataType">

	                                </div>
	
	                                
	                                <div class="row data-type" id="items">
	                                	 <table class="table table-bordered table-striped table-hover dataTable">
						                    <thead id="option">

								            </thead>
						                    <tbody id="optionsInfo">

						                    </tbody>
									 	</table>

	                                </div>
	                                
	                            </div>
                            </div>
                            
                        </div>
                        <!--tab内容/-->
						<!--表单内容/-->
							 
                    </div>
                 	
                 	
                 	
                 	
                   </div>
                  <div class="btn-toolbar list-toolbar">
				      <button class="btn btn-primary" onclick="saveGoods()" ><i class="fa fa-save"></i>保存</button>
				      <button class="btn btn-default" >返回列表</button>
				  </div>
			
            </section>
            
            
<!-- 上传窗口 -->
<div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog" >
	<div class="modal-content">
		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
			<h3 id="myModalLabel">上传商品图片</h3>
		</div>
		<div class="modal-body">							
			
			<table class="table table-bordered table-striped">
		      	<tr>
		      		<td>颜色</td>
		      		<td><input  class="form-control" id="color" placeholder="颜色" >  </td>
		      	</tr>			    
		      	<tr>
		      		<td>商品图片</td>
		      		<td>
						<div class="form-group">
							<label for="goddsImage" >上传图片</label>
							<input type="file" multiple class="form-control" name="myFile" id="goddsImage">
							<input type="text" name="aimg" id="aimg">
						</div>
		      		</td>
		      	</tr>		      	
			 </table>				
			
		</div>
		<div class="modal-footer">						
			<button class="btn btn-success"  data-dismiss="modal" onclick="saveImage()" aria-hidden="true">保存</button>
			<button class="btn btn-default" data-dismiss="modal" aria-hidden="true">关闭</button>
		</div>
	  </div>
	</div>
</div>

            
            <!-- 正文区域 /-->
<script type="text/javascript">

	var editor;
	KindEditor.ready(function(K) {
		editor = K.create('textarea[name="content"]', {
			allowFileManager : true,
			afterBlur: function(){this.sync();}
		});
	});

</script>
       
</body>

</html>
<script>
	$(function () {
		getItemCat(0)
		$('#goddsImage').fileinput({
			language: 'zh',
			uploadUrl: "http://localhost:9002/file/upload",
			browseClass: 'btn btn-primary',
			maxFileCount: 3,//最多支持上传的个数
			enctype: 'multipart/form-data',
			maxFileSize: 1024, //单位为kb, 如果为0表示不限制文件大小
			allowedFileExtensions: ['jpg', 'gif', 'png'],
			// initialPreviewAsData : true, // 初始化预览图片
			// initialPreviewFileType : 'image',// 回显文件类型,
			// initialPreview : "<%=path%>/file/download?filename=${article.aimg}",
		});

		$("#goddsImage").on("fileuploaded", function(event, data, previewId, index){
			if(data.response){
				$("#aimg").val(data.response.imgUrl);
			}
		})
	})
	function getItemCat(parentId) {
		$.ajax({
			url : "http://localhost:9002/goods/listItemCatByPid/" + parentId,
			dataType : "json",
			type : "get",
			success : function (data) {
				if (data.code == 200) {
					var itemCatList = data.data.itemCatList;
					var options = "";
					options += "<option value='-1'>请选择</option>"
					for (var i = 0; i < itemCatList.length; i++) {
						options += "<option value='"+itemCatList[i].id+"'>"+itemCatList[i].name+"</option>"
					}
					$("#oneItemCat").html(options);
				} else {
					alert(data.message);
				}
			}
		})
	}

	function changeOptions(flag) {
		var parentId = 0;
		if (flag == 1) {
			parentId = $("#oneItemCat").val()
		} else if (flag == 2) {
			parentId = $("#twoItemCat").val()
		}
		$.ajax({
			url : "http://localhost:9002/goods/listItemCatByPid/" + parentId,
			dataType : "json",
			type : "get",
			success : function (data) {
				if (data.code == 200) {
					var itemCatList = data.data.itemCatList;
					var options = "";
					options += "<option value='-1'>请选择</option>"
					for (var i = 0; i < itemCatList.length; i++) {
						options += "<option value='"+itemCatList[i].id+"'>"+itemCatList[i].name+"</option>"
					}
					if (flag == 1) {
						$("#twoItemCat").html(options);
					} else if (flag == 2) {
						$("#threeItemCat").html(options);
					}

				} else {
					alert(data.message);
				}
			}
		})


	}

	function itemCat() {
		var id = $("#threeItemCat").val();
		$.ajax({
			url : "http://localhost:9001/itemCat/itemCatById/" + id,
			dataType : "json",
			type : "post",
			async: false,
			success : function (data) {
				if (data.code == 200) {
					$("#templateId").html(data.data.typeId)
				} else {
					alert(data.message)
				}
			},
			error : function (e) {
				alert("系统错误");
				console.log(e)
			}
		})
		getBrand()
		getTemplateById()
	}

	function getTemplateById() {
		var id = $("#templateId").text();
		$.ajax({
			url : "http://localhost:9001/specification/getSpecAndOptionByTypeId",
			dataType : "json",
			type : "post",
			data : {
				templateId : id
			},
			success :function (data) {
				if (data.code == 200) {
					console.log(data.data)
					var html = '';
					$.each(data.data,function (i,e) {
						html +='<div><div class="col-md-2 title">'+e.text+'</div>'
						html +='<div class="col-md-10 data">';
						$.each(e.options,function (index,ele) {
							html +='<span>'
							html +='<input  onclick="checkSpec(this,\''+e.text+'\',\''+ele.optionName+'\')" ' +
									'type="checkbox" value="'+ele.id+'" >'+ele.optionName+'</span>'

						})
						html +='</div></div>'

					});
					$("#dataType").html(html)
				} else {
					alert(data.message)
				}

			}
		})
	}
	var items = [];
	//勾选规格选项复选框函数
	function checkSpec(event,name,value){
		//调用方法判断原集合中是否已有attributeName
		var obj = searchObjectByKey(items,'attributeName',name);
		if(obj != null){
			if($(event).prop('checked')){//勾选
				//如果之前有数据，往原有的对象中追加
				obj.attributeValue.push(value);
			}else{//取消勾选
				obj.attributeValue.splice(obj.attributeValue.indexOf(value),1)//从items中移除规格选项
				//如果规格选项没有数据了
				if(obj.attributeValue.length==0){
					//移除items中的数据
					items.splice(items.indexOf(obj),1)
				}
			}
		}else{
			//如果之前没有数据，items新加数据
			items.push({'attributeName':name,'attributeValue':[value]});
		}
		console.log(items);
		// $("#items").html(JSON.stringify(items))
		//后续调用，这里先不调用，后续选择之后组装选择后的数据用的
		createItemList();
	}

	//遍历组装用户勾选规格选项数据
	function searchObjectByKey(list,attributeName,attributeValue){
		for(var i=0;i<list.length;i++){
			//如果list中我们选择key存在
			if(list[i][attributeName] == attributeValue){
				return list[i];//返回当前对象
			}
		}
		//遍历结束后都不存在，返回null
		return null;
	}

	var skuList;

	//创建SKU列表
	function createItemList() {
		//创建初始值
		var itemList = [{spec: {}}];
		for (var i = 0; i < items.length; i++) {
			itemList = addColum(itemList, items[i].attributeName, items[i].attributeValue);
		}
		skuList = itemList;
		// console.log(items);
		// console.log(itemList);
		var content = '';
		// 拼接列
		for (var i = 0; i < items.length; i++) {
			content += '<th class="sorting">' + items[i].attributeName + '</th>';
		}
		content += '<th class="sorting">价格</th><th class="sorting">库存</th>';
		content += '<th class="sorting">是否启用</th><th class="sorting">是否默认</th>';
		$("#option").html("");
		$("#option").html(content);
		// 拼接行
		var html = '';
		for (var i = 0; i < itemList.length; i++) {
			html += '<tr>';
			for (var j = 0; j < items.length; j++) {
				html += '<td>' + itemList[i].spec[items[j].attributeName] + '</td>';
			}
			html += '<td><input class="form-control" placeholder="价格"></td>';
			html += '<td><input class="form-control" placeholder="库存数量"></td>';
			html += '<td><input type="checkbox" name=""></td>';
			html += '<td><input type="checkbox"></td>';
			html += '</tr>';
		}
		$("#optionsInfo").html("");
		$("#optionsInfo").html(html);
	}

	//添加表格的列
	function addColum(list, columName, columValues) {
		//定义新集合接收行
		var newList = [];
		for (var i = 0; i < list.length; i++) {
			var oldRow = list[i];
			for (var j = 0; j < columValues.length; j++) {
				var newRow = JSON.parse(JSON.stringify(oldRow)); //深克隆
				newRow.spec[columName] = columValues[j];
				newList.push(newRow)
			}
		}
		return newList;
	}

	/**
	 * 获取品牌 扩展属性
	 */
	function getBrand() {
		var id = $("#templateId").text();
		$.ajax({
			url : "http://localhost:9001/template/templateById/"+id,
			dataType : "json",
			type : "get",
			async: false,
			success : function (data) {
				if (data.code == 200) {
					var option = "";
					var template = data.data;
					var brand = JSON.parse(template.brandIds);
					console.log(brand)
					var customAttributeItems = JSON.parse(template.customAttributeItems);

					for (var i = 0; i < brand.length; i++) {
						option += "<option value='"+brand[i].id+"'>"+brand[i].text+"</option>"
					}
					var tr = "";
					for (var i = 0; i < customAttributeItems.length; i++) {
						tr += "<tr>"
						tr += "<td><input type='text' class='form-control'   value='"+customAttributeItems[i].text+"' /></td>"
						tr += "<td><input type='text' class='form-control' placeholder='属性值'  /></td>"
						tr += "</tr>"
					}

					$("#brand").html(option)
					$("#extend").html(tr)
				} else {
					alert(data.message)
				}
			}
		})
	}
	function saveImage() {
		addTable()
	}
	// 动态添加表格
	function addTable() {
		var color = $("#color").val()
		var imagePath = $("#aimg").val()
		var tr = "";
		tr += "<tr>"
		tr += "<td><input type='text' class='icheckbox_square-blue' placeholder='颜色' value='"+color+"' /></td>"
		tr += "<td><input type='text' class='form-control' placeholder='属性名称' value='"+imagePath+"' /></td>"
		tr += '<td><button type="button" class="btn btn-default" onclick="deleteTable(this);" title="删除">删除</button> </td>'
		tr += "</tr>"
		$("#table").append(tr)

	}
	// 移除当前td
	function deleteTable(nowTr) {
		$(nowTr).parent().parent().remove();

	}

	function saveGoods() {
		console.log(editor)
		console.log($("#introduction").val())
		var optionList = [];
		var trs = $("#table").contents().find("tr").prevObject;
		trs.filter("tr");
		for (var i = 0; i < trs.length; i++) {
			var tds = $(trs[i]).find("td");
			var color = $(tds[0]).find("input").val();
			var image = $(tds[1]).find("input").val();
			if (color != null && color != undefined && color != "") {
				var options = {"color":color,"image":image};
				optionList.push(options);
			}
		}
		var specOption = JSON.stringify(optionList);

		var extend = [];
		var extendTrs = $("#extend").contents().find("tr").prevObject;
		extendTrs.filter("tr");
		console.log(extendTrs)
		for (var i = 0; i < extendTrs.length; i++) {
			var tds = $(extendTrs[i]).find("td");
			console.log(tds)
			var text = $(tds[0]).find("input").val();
			var value = $(tds[1]).find("input").val();
			if (text != null && text != undefined && text != "") {
				var options = {"text":text,"value":value};
				extend.push(options);
			}
		}
		var extendJson = JSON.stringify(extend);
		console.log(extendJson)
		// 获取sku
		var itemPrice;
		var number;
		var skuTrs = $("#optionsInfo").contents().find("tr").prevObject;
		console.log(skuTrs)
		var item_sn = 0;
		if ($("#item_sn").prop("checked")) {
			item_sn = 1;
		}
		var itemList = [];
		if (skuTrs.length >= 1) {
			for (var i = 0; i < skuTrs.length; i++) {
				// 获取价格
				itemPrice = ($(skuTrs[i]).find("input")[0].value);
				// 获取库存
				number = ($(skuTrs[i]).find("input")[1].value);
				var defaultFlag = ($(skuTrs[i]).find("input")[3].checked);
				var isDefault = 0;
				// console.log(defaultFlag);
				if (defaultFlag) {
					isDefault = 1;
				}
				var itemsInfo = {
					price: itemPrice,
					num: number,
					stockCount: number,
					isDefault: isDefault,
					categoryId: $("#threeItemCat").val(),
					itemSn: item_sn,
					title: $("#goodsName").val()
				};
				itemList.push(itemsInfo);
			}
		}

		var JsonItemList = JSON.stringify(itemList);
		console.log(JsonItemList)
		console.log(skuList)
		var skuListPut = []
		for (var i = 0; i < skuList.length; i++) {
			skuListPut.push(skuList[i].spec)
		}
		$.ajax({
			url : "http://localhost:9002/goods/saveGoods",
			dataType : "json",
			type : "post",
			data : {
				category1Id : $("#oneItemCat").val(),
				category2Id : $("#twoItemCat").val(),
				category3Id :$("#threeItemCat").val(),
				goodsName : $("#goodsName").val(),
				defaultItemId : $("#templateId").text(),
				brandId : $("#brand").val(),
				caption : $("#caption").val(),
				price : $("#price").val(),
				introduction : $("#introduction").val(),
				packageList : $("#packageList").val(),
				saleService : $("#saleService").val(),
				specificationItems : JSON.stringify(items),
				itemImages : specOption,
				customAttributeItems : extendJson,
				item : JsonItemList,
				skuList : JSON.stringify(skuListPut)
			},
			success : function (data) {
				alert(data.message)
			}
		})
	}

</script>